package com.sunday.volunteer.ui;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.sunday.common.adapter.MainFragmentPagerAdapter;
import com.sunday.common.event.EventBus;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.Constants;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.UIAlertView;
import com.sunday.member.base.BaseActivity;
import com.sunday.member.event.ExitApp;
import com.sunday.member.utils.SharePerferenceUtils;
import com.sunday.volunteer.BaseApp;
import com.sunday.volunteer.R;
import com.sunday.volunteer.entity.Member;
import com.sunday.volunteer.fragment.tab.IndexFragment;
import com.sunday.volunteer.fragment.tab.IndexMapFragment;
import com.sunday.volunteer.fragment.tab.MineFragment;
import com.sunday.volunteer.fragment.tab.ShopFragment;
import com.sunday.volunteer.http.HttpClient;
import com.sunday.volunteer.weights.ViewPager;


import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends BaseActivity {
    @Bind(R.id.content)
    ViewPager viewPager;
    private IndexFragment indexFragment;
    private ShopFragment shopFragment;
    private MineFragment mineFragment;
    private IndexMapFragment indexTwoFragment;

    private ArrayList<Fragment> fragments;
    private MyLocationListener myLocationListener;

    private int indexId = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        fragments = new ArrayList<>(3);

        indexFragment = new IndexFragment();
        indexTwoFragment = new IndexMapFragment();
        shopFragment = new ShopFragment();
        mineFragment = new MineFragment();

        fragments.add(indexFragment);
        fragments.add(indexTwoFragment);
        fragments.add(shopFragment);
        fragments.add(mineFragment);

        viewPager.setAdapter(new MainFragmentPagerAdapter(getSupportFragmentManager(), fragments));
        viewPager.setOffscreenPageLimit(4);
        updateUser();

        toLocation();
    }

    public void setPager(int position){
        indexId = position;
        viewPager.setCurrentItem(indexId, false);
    }



    @OnClick(R.id.tab01)
    void index(){
        viewPager.setCurrentItem(indexId, false);
    }


    @OnClick(R.id.tab02)
    void shop(){
        viewPager.setCurrentItem(2,false);
    }

    @OnClick(R.id.tab03)
    void income(){
        viewPager.setCurrentItem(3,false);
    }


    private boolean isNeedRunning = true;
    private long exitTime = 0;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
            if((System.currentTimeMillis()-exitTime) > 2000){
                Toast.makeText(mContext, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                isNeedRunning = false;
                EventBus.getDefault().post(new ExitApp());
                System.exit(1);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume() {
        super.onResume();
        updateUser();
    }

    public void updateUser(){
        Call<ResultDO<Member>> call = HttpClient.getHttpAdapter().getMemberDeatail(BaseApp.getInstance().getMemberId());
        call.enqueue(new Callback<ResultDO<Member>>() {
            @Override
            public void onResponse(Call<ResultDO<Member>> call, Response<ResultDO<Member>> response) {
                if(response.body() == null || isFinish ){
                    return;
                }
                if(response.body().getCode() == 0 && response.body().getResult()!= null){
                    Member member = response.body().getResult();
                    SharePerferenceUtils.getIns(mContext).saveOAuth(member);
                    mineFragment.setData(member);
                    shopFragment.setData(member);
                    indexFragment.setData(member);
                }else {
                    ToastUtils.showToast(mContext , response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<Member>> call, Throwable t) {

            }
        });
    }
    public void toLocation(){
        PackageManager pkgManager =getPackageManager();
        boolean checkPermission = pkgManager.checkPermission( Manifest.permission.ACCESS_COARSE_LOCATION ,getPackageName()) == PackageManager.PERMISSION_GRANTED;

        if (Build.VERSION.SDK_INT >= 23 && !checkPermission) {
            requestPermissions(new String[] { Manifest.permission.ACCESS_COARSE_LOCATION },0);
        } else {
            // SDK初始化，第三方程序启动时，都要进行SDK初始化工作
            //PushManager.getInstance().initialize(this.getApplicationContext());
            myLocationListener = new MyLocationListener();
            BaseApp.getInstance().mLocationClient.registerLocationListener(myLocationListener);
            BaseApp.getInstance().mLocationClient.start();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 0:
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED ) {
                    // SDK初始化，第三方程序启动时，都要进行SDK初始化工作
                    //PushManager.getInstance().initialize(this.getApplicationContext());
                    myLocationListener = new MyLocationListener();
                    BaseApp.getInstance().mLocationClient.registerLocationListener(myLocationListener);
                    BaseApp.getInstance().mLocationClient.start();
                } else {
                    //checkMMS();
                    show();
                }
                return;
        }
    }

    private void show(){
        final UIAlertView view = new UIAlertView(mContext , "温馨提示" , "权限已被关闭，是否需要重新设置" , "取消" , "确定");
        view.setClicklistener(new UIAlertView.ClickListenerInterface() {
            @Override
            public void doLeft() {
                view.dismiss();
            }

            @Override
            public void doRight() {
                view.dismiss();
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_SETTINGS);
                startActivity(intent);
            }
        });
        view.show();
    }

    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location.getLatitude() != 0) {
                SharePerferenceUtils.getIns(mContext).putString(Constants.LATITUDE, String.valueOf(location.getLatitude()));
            }
            if (location.getLongitude() != 0) {
                SharePerferenceUtils.getIns(mContext).putString(Constants.LONGITUDE, String.valueOf(location.getLongitude()));
            }
            if (!TextUtils.isEmpty(location.getAddrStr())) {
                SharePerferenceUtils.getIns(mContext).putString(Constants.LOCATION_ADDRESS, location.getAddrStr());
            }
            if (!TextUtils.isEmpty(location.getProvince())) {
                SharePerferenceUtils.getIns(mContext).putString(Constants.LOCATION_PROVINCE, location.getProvince());
            }
            if (!TextUtils.isEmpty(location.getCity())) {
                SharePerferenceUtils.getIns(mContext).putString(Constants.LOCALTION_CITY, String.valueOf(location.getCity()));
            }
            if (!TextUtils.isEmpty(location.getDistrict())) {
                SharePerferenceUtils.getIns(mContext).putString(Constants.LOCALTION_DISTRCT, String.valueOf(location.getDistrict()));
            }
            BaseApp.getInstance().mLocationClient.stop();
        }
    }



}
